package io.jpress.module.article.controller.api;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.web.controller.annotation.RequestMapping;

import io.jpress.model.User;
import io.jpress.module.article.model.ArticleGoods;
import io.jpress.module.article.service.ArticleGoodsService;
import io.jpress.service.UserService;
import io.jpress.web.base.ApiControllerBase;

import javax.inject.Inject;

@RequestMapping("/api/goods")
public class GoodsApiController extends ApiControllerBase {

    @Inject
    private ArticleGoodsService articleGoodsService;
    @Inject
    private UserService userService;

    /**
     * 分页查询用户录入的商品信息
     */
    public void userGoodsPage(){
        User user = getLoginedUser();
        if (user == null) {
            renderFailJson(1, "user not logined");
            return;
        }
        int pageNumber = getParaToInt("page", 1);
        Page<ArticleGoods> page =  articleGoodsService._paginateByUserId(pageNumber,10,user.getId());
        renderJson(Ret.ok().set("page", page));
    }

    /**
     * 保存编辑录入的商品信息
     */
    public void save(){
        ArticleGoods articleGoods = getRawObject(ArticleGoods.class);
        User user = getLoginedUser();
        if (user == null) {
            renderFailJson(1, "user not logined");
            return;
        }
        //判断用户是否被冻结
        user = userService.findById(user.getId());
        if(!user.isStatusOk()){
            renderFailJson(1, "您的账号已被冻结!");
            return;
        }
        articleGoods.setUserId(user.getId());
        articleGoodsService.saveOrUpdate(articleGoods);
        renderJson(Ret.ok());
    }

    /**
     * 删除商品信息
     */
    public void delete(){
        Long id = getParaToLong("goodsId");

        ArticleGoods articleGoods = articleGoodsService.findById(id);
        if(articleGoods == null){
            renderFailJson("无效的商品id");
            return;
        }
        articleGoods.setDelFlag("1");
        articleGoodsService.update(articleGoods);
        renderJson(Ret.ok());
    }

    /**
     * 文章商品关联
     */
    public void linkArticleGoods(){
        Long articleId = getParaToLong("articleId");
        Long[] goodsIds = getParaValuesToLong("goodsIds");
        if(articleId == null || goodsIds == null || goodsIds.length<=0){
            renderFailJson("参数有误");
            return;
        }
        articleGoodsService.linkArticleGoods(articleId,goodsIds);
        renderJson(Ret.ok());
    }










}
